<template>
  <div class="sms_template">
    <!-- 搜索条件 -->
    <div class="header">
      <div class="btn_group">
        <HPlainButton v-permission="'note_sync'" @click="onSync">同步模版</HPlainButton>

        <!--批量操作-->
        <el-dropdown trigger="click">
          <HButton :disabled="ids.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <div  v-permission="'note_enabled'">
                <el-dropdown-item @click="handleChangeAll(false, '启用')">
                  <el-icon>
                    <CircleCheck />
                  </el-icon>
                  批量启用
                </el-dropdown-item>
              </div>
              <div v-permission="'note_disabled'">
                <el-dropdown-item @click="handleChangeAll(true, '禁用')">
                  <el-icon>
                    <Warning />
                  </el-icon>
                  批量禁用
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <!-- 模版类型 -->
        <el-select
          v-model="filter.type"
          clearable
          placeholder="请选择"
          @change="getSmsTemplateList"
          @clear="getSmsTemplateList"
        >
          <el-option
            v-for="item in typeOptional"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- 模版名称/模版内容 -->
        <el-input
          v-model.trim="filter.keyword"
          clearable
          placeholder="模版名称/模版内容"
          @clear="getSmsTemplateList"
          @keyup.enter="getSmsTemplateList"
        />
        <HButton type="primary" @click="getSmsTemplateList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
        <HButton @click="onReset">
          <el-icon>
            <RefreshRight />
          </el-icon>
          重置
        </HButton>
      </div>
    </div>
    <div
      v-loading="getSmsTemplateListLoading || syncSmsTemplateLoading || updateSmsTemplateLoading"
      class="table"
    >
      <el-table
        :data="smsTemplateList"
        border
        resizable
        stripe
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <!--选择-->
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />

        <!-- 序号 -->
        <el-table-column label="序号" type="index" width="50" fixed="left" :align="'center'" />

        <!-- 模版名称 -->
        <el-table-column label="模版名称" prop="name" show-overflow-tooltip width="160" />

        <!-- 模版类型 -->
        <el-table-column label="模版类型" prop="type" show-overflow-tooltip width="86">
          <template #default="scope">
            <span v-if="scope.row.type === 1">验证类短信</span>
            <span v-else-if="scope.row.type === 2">通知类</span>
            <span v-else>推广类</span>
          </template>
        </el-table-column>

        <!-- 模版编号 -->
        <el-table-column label="模版编号" prop="code" show-overflow-tooltip width="160" />

        <!-- 模版内容 -->
        <el-table-column label="模版内容" min-width="150" prop="content" show-overflow-tooltip />

        <!-- 人员类型 -->
        <el-table-column label="人员类型" prop="roleTypeStr" show-overflow-tooltip width="90" />

        <!-- 创建时间 -->
        <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip width="128" />

        <!-- 更新时间 -->
        <el-table-column label="更新时间" prop="updateTime" show-overflow-tooltip width="128" />

        <!-- 发布状态 -->
        <el-table-column label="发布状态" prop="release" width="84" fixed="right" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="scope.row.release">已发布</HStatus>
              <HStatus v-else type="info">已下架</HStatus>
            </div>
          </template>
        </el-table-column>

        <!-- 是否发布 -->
        <el-table-column label="是否启用" prop="status" width="80" fixed="right" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="!scope.row.status">启用</HStatus>
              <HStatus v-else type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" width="135">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink v-permission="'note_update'" v-if="scope.row.updateReceiveRole" @click="onUpdateReceiveType(scope.row.id)"
                >修改</HLink
              >
              <SmsTemplateDetail v-permission="'note_showDetail'" :sms-template-id="scope.row.id" @update="getSmsTemplateList">
                <HLink>详细</HLink>
              </SmsTemplateDetail>
              <HLink v-permission="'note_enabled'" v-if="scope.row.status" @click="handleChange(scope.row.id, false, '启用')"
                >启用</HLink
              >
              <HLink v-permission="'note_disabled'" v-else @click="handleChange(scope.row.id, true, '禁用')">禁用</HLink>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <Pagination
        ref="paginationRef"
        :list_total="Number(totalList)"
        @size-change="getSmsTemplateList"
        @current-change="getSmsTemplateList(false)"
      />
    </div>

    <update-receiver-type
      v-model:visible="updateReceiverTypeDialogVisible"
      :sms-template-id="currentUpdateReciverTypeSmsTemplateId"
      @updated="getSmsTemplateList(false)"
    ></update-receiver-type>
  </div>
</template>

<script lang="ts" setup>
  import Pagination from '@/components/Pagination/index.vue'
  import { onMounted, ref, h } from 'vue'
  import { ArrowDown, CircleCheck, RefreshRight, Search, Warning } from '@element-plus/icons-vue'
  import smsListService from './services/list'
  import smsDetailService from './services/detail'
  import SmsTemplateDetail from './components/SmsTemplateDetail.vue'
  import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
  import { SmsTemplateListItem } from './types'
  import updateReceiverType from '@/components/pages/sms/update-receiver-type.vue'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.note.noteTemplateList,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const {
    totalList,
    smsTemplateList,
    syncSmsTemplateLoading,
    getSmsTemplateListLoading,
    getSmsTemplatesFn,
    syncSmsTemplateFn,
  } = smsListService

  // 分页组件实例
  const paginationRef = ref<InstanceType<typeof Pagination> | null>(null)

  // 筛选条件
  const filter = ref({
    keyword: '',
    type: null,
  })

  // 类型选择
  const typeOptional = [
    { value: '1', label: '验证类短信' },
    { value: '2', label: '通知类' },
    { value: '3', label: '推广类短信' },
  ]

  // 获取短信模版列表
  const getSmsTemplateList = (val = true) => {
    const __filter = getFilter(val)
    getSmsTemplatesFn(__filter)
  }

  // 重置事件
  const onReset = () => {
    Object.assign(filter.value, {
      keyword: '',
      type: null,
    })
    getSmsTemplateList()
  }

  // 处理filter搜索条件
  const getFilter = (val) => {
    const result = {
      page: 1,
      limit: 50,
      keyword: '',
      type: null,
    }

    result.keyword = filter.value.keyword
    result.type = filter.value.type

    if (paginationRef.value) {
      if (val) paginationRef.value.setPage()
      result.page = paginationRef.value.current
      result.limit = paginationRef.value.size
    }

    return result
  }

  // 同步事件
  const onSync = async () => {
    const res = await syncSmsTemplateFn()
    getSmsTemplateList()
    ElMessage({
      type: res.code === 20000 ? 'success' : 'error',
      message: res.message,
      duration: 5000,
      showClose: true,
      plain: true,
    })
  }

  // 选中的列
  const ids = ref<Array<number | string>>([])

  // 表格多选事件
  const handleSelectionChange = (smsTemplateList: Array<SmsTemplateListItem>) => {
    ids.value = []
    smsTemplateList.filter((o) => {
      ids.value.push(o.id)
    })
  }

  const { updateSmsTemplateFn, updateSmsTemplateLoading } = smsDetailService

  // 批量修改状态事件
  const handleChangeAll = (status: boolean, str: string) => {
    if (ids.value.length == 0) {
      ElMessage({
        message: `请选择要${str}的短信模版`,
        type: 'warning',
        duration: 5000,
        showClose: true,
        plain: true,
      })
      return
    }
    ElMessageBox({
      title: '提示',
      message: `确定${str}该短信模版?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    }).then(async () => {
      const res = await updateSmsTemplateFn(ids.value, status)
      getSmsTemplateList()
      ElMessage({
        type: res.code === 20000 ? 'success' : 'error',
        message: res.message,
        duration: 5000,
        showClose: true,
        plain: true,
      })
    })
  }

  // 修改单个状态事件
  const handleChange = (id: string | number, status: boolean, str: string) => {
    ElMessageBox({
      title: '提示',
      message: `确定${str}该短信模版吗?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    }).then(async () => {
      const res = await updateSmsTemplateFn([id], status)
      getSmsTemplateList()
      ElMessage({
        type: res.code === 20000 ? 'success' : 'error',
        message: res.message,
        showClose: true,
        duration: 5000,
        plain: true,
      })
    })
  }

  // 当前正在更改接收者类型的短信模板id
  const currentUpdateReciverTypeSmsTemplateId = ref('')

  // 更新接收者类型弹窗显示状态
  const updateReceiverTypeDialogVisible = ref(false)

  /**
   * 更新接收者类型
   * @param {String} smsTemplateId - 短信模板id
   */
  const onUpdateReceiveType = (smsTemplateId: string) => {
    currentUpdateReciverTypeSmsTemplateId.value = smsTemplateId
    updateReceiverTypeDialogVisible.value = true
  }

  onMounted(() => {
    getSmsTemplateList()
  })
</script>

<style lang="scss" scoped>
  @import './index';
</style>
